package com.example.chatgpt;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chatgpt.bean.User;
import com.example.chatgpt.dao.UserDao;
import com.example.chatgpt.entity.UserInfo;
import com.example.chatgpt.util.CloseKeyBoardUtil;
import com.example.chatgpt.util.StatusBarUtil;

import java.util.List;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_user;
    private EditText et_password;
    private TextView tv_forget;
    private UserDao userDao;
    private User userInfo;
    private MyApplication myApplication;
    private SharedPreferences.Editor userEdit;
    private ImageButton ib_hidden;
    //文本编辑框内容隐藏显示标志
    private boolean hiddenFlag = false;
    private EditText updatePass;
    private EditText confirmPass;
    private TextView updateUser;
    private SharedPreferences userPreferences;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //设置状态栏字体为黑色
       StatusBarUtil.setStatusBarTextColorBlack(this);

        et_user = findViewById(R.id.et_user);
        et_password = findViewById(R.id.et_password);
        tv_forget = findViewById(R.id.forget_password);
        ib_hidden = findViewById(R.id.ib_hidden);
        //设置点击事件
        tv_forget.setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        ib_hidden.setOnClickListener(this);

        myApplication = (MyApplication) getApplication();
        userDao = myApplication.getUserDao();
        userInfo = myApplication.getUserInfo();
        int quitFlag = userInfo.getQuitFlag();

        userPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        userEdit = userPreferences.edit();

        //从我的界面退出登陆后跳转到该界面 并且使文本输入框清空 不执行reload()
        if (quitFlag == 0) {
            reload();
        } else {
            et_user.setText("");
            et_user.setText("");
            et_user.requestFocus();
            userEdit.putString("user", "");
            userEdit.putString("password", "");
            userEdit.commit();
        }


    }

    private void reload() {
        String user = userPreferences.getString("user", "");
        if (!user.equals("")) {
            et_user.setText(user);
        } else {
            return;
        }
        String password = userPreferences.getString("password", "");
        if (!password.equals("")) {
            et_password.setText(password);
        }
        userInfo.setUser(user);
        Intent intent = new Intent(this, ChatGPTActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                String mUser = et_user.getText().toString();
                String mPassword = et_password.getText().toString();
                List<UserInfo> userInfos = userDao.queryByUser(mUser);
                Log.d("guaimiao", String.valueOf(userInfos.size()));
                //文本判空
                if (!mUser.equals("") && !mPassword.equals("")) {
                    //如果不存在账号直接添加到数据库 创建账号
                    if (userInfos.isEmpty()) {
                        Toast.makeText(this, "创建用户成功!", Toast.LENGTH_SHORT).show();
                        userInfo.setUser(mUser);
                        userEdit.putString("user", mUser);
                        userEdit.putString("password", mPassword);
                        userEdit.commit();
                        userDao.insertUser(new UserInfo(mUser, mPassword));
                        Intent intent = new Intent(this, ChatGPTActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        return;
                    }
                    //如果账号能查询到 但是密码不对 则提示密码错误
                    if (userInfos.get(0).user.equals(mUser) && !userInfos.get(0).password.equals(mPassword)) {
                        et_password.requestFocus();
                        Toast.makeText(this, "账号密码错误请重新输入!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //如果密码和账号全对直接登录
                    if (userInfos.get(0).user.equals(mUser) && userInfos.get(0).password.equals(mPassword)) {
                        userInfo.setUser(mUser);
                        userEdit.putString("user", mUser);
                        userEdit.putString("password", mPassword);
                        userEdit.commit();
                        Intent intent = new Intent(this, ChatGPTActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        return;
                    }
                } else {
                    et_user.requestFocus();
                    Toast.makeText(this, "账户密码不能为空", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.ib_hidden:
                hiddenFlag = !hiddenFlag;
                //切换显示隐藏模式
                if (hiddenFlag) {
                    ib_hidden.setBackground(null);
                    ib_hidden.setImageResource(R.mipmap.password_show);
                    et_password.setTransformationMethod(new HideReturnsTransformationMethod());
                } else {
                    ib_hidden.setImageResource(R.mipmap.password_hidden);
                    et_password.setTransformationMethod(new PasswordTransformationMethod());
                }
                //切换后将光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
                break;
            case R.id.forget_password:
                initUpdatePasswordDialog();
                break;
        }
    }

    @SuppressLint("MissingInflatedId")
    private void initUpdatePasswordDialog() {
        Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        //获取布局文件
        View view = LayoutInflater.from(this).inflate(R.layout.update_password, null);
        //加入布局
        bottomDialog.setContentView(view);
        //设置参数
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels;
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        updateUser = view.findViewById(R.id.et_update_user);
        updatePass = view.findViewById(R.id.et_update_password);
        confirmPass = view.findViewById(R.id.et_confirm_password);
        view.findViewById(R.id.btn_confirm_update).setOnClickListener(view1 -> {
            switch (view1.getId()) {
                case R.id.btn_confirm_update:
                    String mUpdateUser = updateUser.getText().toString();
                    String mUpdatePass = updatePass.getText().toString();
                    String mConfirmPass = confirmPass.getText().toString();
                    List<UserInfo> userInfos = userDao.queryByUser(mUpdateUser);
                    //先判断要修改密码的账户存不存在
                    if (userInfos.isEmpty()) {
                        CloseKeyBoardUtil.hideOneInputMethod(this, view);
                        updateUser.requestFocus();
                        Toast.makeText(this, "该用户不存在，请检查用户名是否正确", Toast.LENGTH_SHORT).show();
                    } else {
                        //如果存在账户 判断修改的密码和确认修改的密码是否一样
                        if (mUpdatePass.equals(mConfirmPass)) {
                            //判断修改的密码是否和原密码一样
                            if (!mUpdatePass.equals(userInfos.get(0).password)) {
                                userDao.updatePass(userInfos.get(0).user, mUpdatePass);
                                bottomDialog.dismiss();
                                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT);
                            } else {
                                CloseKeyBoardUtil.hideOneInputMethod(this, view);
                                updatePass.requestFocus();
                                Toast.makeText(this, "修改的密码不能与原密码相同，请重新输入", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            //如果两次密码输入不一样
                            CloseKeyBoardUtil.hideOneInputMethod(this, view);
                            updatePass.requestFocus();
                            Toast.makeText(this, "两次密码不一致，请检查两次密码的输入是否相同", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        });
    }

}